<template>
  <div>
    <div class="pd20">
      <div class="row-spaceb">
        <p class="fwbold fs-md">服务产品上架</p>
        <el-button
          type="primary"
          size="medium"
          plain
          @click="goBackList"
        >返回</el-button>
      </div>
      <div class="fs12 color-warning mt10">
        （一）各服务商对所申报产品，应做好定性和定量描述工作，材料内容可充分展示必要佐证及产品比较优势，如有相关资质、优秀案例等可一并上传提供。如：高阶检测检验服务类产品，提供该服务在国内外同行的自我评价分析、硬件条件、人才团队优势、认证资质、案例等材料，在专家评价环节将作为重要参考依据；中高端市场开拓产品，提供该服务于产业链供应链体系中起到的关键作用、为服务对象参与头部企业或龙头企业供应合作、产品出口海外市场、提升服务对象产品溢价或盈利能力等，在专家评价环节将作为重要参考依据；诊断、技术创新、数字化转型、融资等其他类型产品，如能提供关键要素分析，呈现性价比较高的内容及必要佐证，在专家评价环节均可作为重要参考依据。（二）未尽事宜按照《自治区工业和信息化厅 自治区财政厅关于印发广西制造业企业培优育强服务券管理办法（试行）的通知》（桂工信规范〔2024〕9号）有关要求执行。
      </div>
      <el-divider></el-divider>
      <div
        class="card"
        v-loading="formLoading"
      >
        <el-form
          :rules="serviceRules"
          ref="serviceForm"
          :model="serviceData"
          label-position="right"
          label-suffix=":"
          size="medium"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="服务产品名称"
                prop="productName"
                label-width="180px"
              >
                <el-input
                  placeholder="请输入服务产品名称"
                  style="width: 85%;"
                  v-model="serviceData.productName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="服务类型"
                prop="productTypeId"
                label-width="120px"
              >
                <el-cascader
                  v-model="serviceData.productTypeId"
                  :options="serviceTypeData"
                  @change="handleServiceTypeChange"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <template v-if="serviceData.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac' || serviceData.parentProductTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac'">
              <el-col :span="8">
                <el-form-item
                  label="产品类型分类"
                  prop="digitalSubtype"
                  label-width="180px"
                >
                  <el-select
                    v-model="serviceData.digitalSubtype"
                    placeholder="请选择产品类型分类"
                    style="width:100%;"
                  >
                    <el-option
                      v-for="item in digitalSubtypeOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item
                  label="行业分类"
                  prop="digitalIndustry"
                  label-width="120px"
                >
                  <el-select
                    v-model="serviceData.digitalIndustry"
                    placeholder="请选择行业分类"
                    multiple
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="item in digitalIndustryOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item
                  label="场景分类"
                  prop="digitalScenarios"
                  label-width="120px"
                >
                  <el-select
                    v-model="serviceData.digitalScenarios"
                    multiple
                    placeholder="请选择场景分类"
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="item in digitalScenariosOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-else>
              <el-col :span="24">
                <el-form-item
                  label="场景分类"
                  prop="digitalScenarios"
                  label-width="180px"
                >
                  <el-select
                    v-model="serviceData.digitalScenarios"
                    multiple
                    placeholder="请选择场景分类"
                    style="width: 93%;"
                  >
                    <el-option
                      v-for="item in digitalScenariosOptions"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-if="!isNegotiablePrice">
              <el-col :span="12">
                <el-form-item
                  label="平台销售价(元)"
                  prop="servicePrice"
                  label-width="180px"
                >
                  <el-input-number
                    v-model="serviceData.servicePrice"
                    controls-position="right"
                    @change="inputPlatform"
                    :min="0"
                    :max="100000000000"
                    :precision="2"
                    :step="100"
                    style="width: 85%;"
                    :disabled="serviceData.auditStatus2 == 1"
                  ></el-input-number>
                  <div class="fs14 color-warning"><i class="el-icon-warning" />在平台期望销售的价格，一般需要低于市场指导价，体现优惠性。<span v-if="serviceData.auditStatus2 == 1">已审核过的产品，下降后从新上架，平台销售价格置灰，不可修改 （若修改审核通过后的产品价格，请联系中小企业发展处）</span></div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="市场指导价(元)"
                  prop="marketPrice"
                  label-width="120px"
                >
                  <el-input-number
                    v-model="serviceData.marketPrice"
                    controls-position="right"
                    @change="inputMarket"
                    :min="0"
                    :max="100000000000"
                    :precision="2"
                    :step="100"
                    style="width: 85%;"
                  ></el-input-number>
                  <div class="fs14 color-warning"><i class="el-icon-warning" />市场指导价格仅做展示，实际以平台销售价格为准</div>
                </el-form-item>
              </el-col>
            </template>
            <template v-else>
              <el-col :span="24">
                <el-form-item
                  label="服务价格"
                  label-width="180px"
                >
                  <span>面议</span>
                  <span class="fs14 color-warning ml20"><i class="el-icon-warning"></i>具体服务金额在签订合同前确定。</span>
                </el-form-item>
              </el-col>
            </template>
            <el-col
              v-if="!isNegotiablePrice"
              :span="24"
            >
              <el-form-item
                label="产品价格测算过程"
                prop="priceCalculationProcess"
                label-width="180px"
              >
                <el-input
                  clearable
                  placeholder="请输入服务产品价格测算过程"
                  v-model="serviceData.priceCalculationProcess"
                  style="width: 93%;"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="联系人"
                prop="contactPerson"
                label-width="180px"
              >
                <el-input
                  v-model="serviceData.contactPerson"
                  placeholder="请输入联系人姓名"
                  style="width: 85%;"
                > </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="联系人电话"
                prop="contactPhoneNum"
                label-width="120px"
              >
                <el-input
                  v-model="serviceData.contactPhoneNum"
                  placeholder="请输入联系人电话"
                  style="width: 85%;"
                ></el-input>
              </el-form-item>
            </el-col>
            <template v-if="serviceData.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac' || serviceData.parentProductTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac'">
              <el-col :span="24">
              <el-form-item
                label="是否为“小快轻准”产品"
                prop="fastGoodShelf"
                label-width="200px"
              >
                <el-radio-group v-model="serviceData.fastGoodShelf">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="是否实现企业上云"
                prop="onLineShelf"
                label-width="200px"
              >
                <el-radio-group v-model="serviceData.onLineShelf">
                  <el-radio :label="0">否</el-radio>
                  <el-radio :label="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            </template>
            
            <el-col
              v-if="!isNegotiablePrice"
              :span="24"
            >
              <el-form-item
                label="产品相关专利及名称"
                prop="patent"
                label-width="180px"
              >
                <el-input
                  clearable
                  placeholder="请输入服务产品相关专利及名称"
                  v-model="serviceData.patent"
                  style="width: 93%;"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col
              v-if="!isNegotiablePrice"
              :span="24"
            >
              <el-form-item
                label="相关专利佐证文件"
                prop="patent"
                label-width="180px"
              >
                <div class="row-start">
                  <div
                    v-if="patentSupportFile"
                    class="mb15"
                    @click="downloadProofFile()"
                  >{{serviceData.patentSupportFileName}} <i
                      v-if="serviceData.patentSupportFileName"
                      class="el-icon-circle-check color-primary mr5"
                    ></i></div>
                  <div
                    v-else-if="patentSupportFileFromDetail"
                    class="mb15 color-primary showMouse mr15"
                    @click="downloadProofFile()"
                  >查看文件 </div>
                  <upload-file
                    v-if="auditStatus === '-1' || !productId"
                    @setFileUrl="upLoadPatentSupportFile($event)"
                  ></upload-file>
                </div>
              </el-form-item>
            </el-col>
            <el-col
              v-if="!isNegotiablePrice"
              :span="24"
            >
              <el-form-item
                label="相关服务资质佐证文件"
                prop="patent"
                label-width="180px"
              >
                <div class="row-start">
                  <div
                    v-if="contactSupportFile"
                    class="mb15"
                    @click="downloadSupportFile()"
                  >{{serviceData.contactSupportFileName}} <i
                      v-if="serviceData.contactSupportFileName"
                      class="el-icon-circle-check color-primary mr5"
                    ></i></div>
                  <div
                    v-else-if="contactSupportFileFromDetail"
                    class="mb15 color-primary showMouse mr15"
                    @click="downloadSupportFile()"
                  >查看文件 </div>
                  <upload-file
                    @setFileUrl="upLoadContactSupportFile($event)"
                  ></upload-file>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                :label="`服务产品主图(${serviceData?.productImg?.length}/3)`"
                prop="productImg"
                label-width="180px"
              >
                <div class="row-start">
                  <div
                    v-if="serviceData.productImg.length >= 1"
                    class="row-start"
                  >
                    <div
                      v-for="(item, index) in serviceData.productImg"
                      :key="index"
                      class="img_box relposition"
                    >
                      <img
                        :src="`/api/public/file/v1/public/get/${item}`"
                        style="width:148px;height:148px"
                        alt=""
                        @error="setDefaultImage"
                      >
                      <el-button
                        icon="el-icon-close"
                        size="mini"
                        circle
                        style="position:absolute;right:5px"
                        @click="removeImage(index)"
                      ></el-button>
                    </div>
                  </div>
                  <div v-else>
                    <img
                      v-if="serviceData?.productImg "
                      :src="`/api/public/file/v1/public/get/${serviceData.productImg}`"
                      style="width:148px;height:148px"
                      alt=""
                      @error="setDefaultImage"
                    >
                  </div>
                  <uploadImage
                    ref="uploadImg"
                    :showFile="false"
                    :limit="3"
                    @setCardPic="setProductImages"
                  ></uploadImage>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="服务产品介绍"
                prop="serviceContent"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="7"
                  placeholder="例:\n服务产品介绍：财务数智化管理软件主要运用新一代人工智能财税引擎,打造企业数字大脑赋能数字经营能力，助其成为区域、行业龙头企业。\n解决问题：软件通过整合各类数据，通过自建业务模型，数字大脑进行分析，核心业务及核心岗位设定关键指标，让经营者随之掌握公司业务状态、精准决策。\n具体效果：有数百家企业通过管理软件提升了经营管理能力，解决了经营者不懂财务盲目决策的弊端，获得了使用者的一致好评。"
                  v-model="serviceData.serviceContent"
                  minlength="200"
                  maxlength="1000"
                  show-word-limit
                  @blur="handleServiceContentBlur"
                ></el-input>
                <div class="fs14 color-warning"><i class="el-icon-warning" />服务产品文字介绍，将体现于商品详情展示及服务合同(200~1000字)，此部分内容将直接读入合同，请务必准确详细填写。</div>
                <el-button
                  type="primary"
                  size="mini"
                  class="mt10"
                  @click="showPreviewDialog = true"
                >预览合同</el-button>
              </el-form-item>
              <el-dialog
                title="重要提示"
                :visible.sync="showServiceContentConfirm"
                width="420px"
              >
                <div>此部分内容将直接读入合同，请务必准确详细填写，填写后可在下方预览合同模板。</div>
                <span
                  slot="footer"
                  class="dialog-footer"
                >
                  <el-button
                    type="primary"
                    @click="showServiceContentConfirm = false"
                  >我知道了</el-button>
                </span>
              </el-dialog>
              <el-dialog
                title="合同预览"
                :visible.sync="showPreviewDialog"
                width="600px"
              >
                <div class="tc">
                  <img
                    :src="require('@/assets/image/preview.png')"
                    alt="合同预览"
                    style="max-width:100%"
                  />
                </div>
                <span
                  slot="footer"
                  class="dialog-footer"
                >
                  <el-button @click="showPreviewDialog = false">关闭</el-button>
                </span>
              </el-dialog>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="服务功能介绍"
                prop="deliveryContent1"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="7"
                  placeholder="服务功能介绍"
                  v-model="serviceData.deliveryContent1"
                  minlength="50"
                  show-word-limit
                ></el-input>
                <div class="fs14 color-warning"><i class="el-icon-warning" />请详细描述功能介绍(至少50字)，此部分内容将作为合同的一部分，构成具有法律效力的服务条款。</div>
              </el-form-item>
              <el-form-item
                label="交付清单"
                prop="deliveryContent2"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="交付清单"
                  v-model="serviceData.deliveryContent2"
                  minlength="50"
                  show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item
                label="验收标准"
                prop="deliveryContent3"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="验收标准"
                  v-model="serviceData.deliveryContent3"
                  minlength="50"
                  show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item
                label="服务流程"
                prop="deliveryContent4"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="服务流程"
                  v-model="serviceData.deliveryContent4"
                  minlength="50"
                  show-word-limit
                ></el-input>
                <el-button
                  type="primary"
                  size="mini"
                  class="mt10"
                  @click="showPreviewDialog = true"
                >预览合同</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                :label="isNegotiablePrice ? '与同行业产品比较的优势' : '产品服务典型案例介绍'"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="6"
                  placeholder="
                      例:
                        1、案例一：
                        2、案例二:
                        3、案例三：
                        ......"
                  v-model="serviceData.advantage"
                  maxlength="3000"
                  show-word-limit
                ></el-input>
                <div class="fs14 color-warning"><i class="el-icon-warning" />将体现于商品详情展示(3000字以内)。</div>
              </el-form-item>
            </el-col>
            <el-col
              v-if="!isNegotiablePrice"
              :span="24"
            >
              <el-form-item
                label="服务产品成果指标"
                prop="achievement"
                label-width="180px"
              >
                <template #label>
                  <span> <span style="color: red">*</span>服务产品成果指标：</span>
                </template>
                <el-form-item
                  label="经济指标"
                  prop="economic"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="serviceData.economic"
                    placeholder="请输入经济指标"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="质量指标"
                  prop="quality"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="serviceData.quality"
                    placeholder="请输入质量指标"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="效率指标"
                  prop="efficiency"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="serviceData.efficiency"
                    placeholder="请输入效率指标"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="其他指标"
                  prop="other"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="serviceData.other"
                    placeholder="请输入其他指标"
                  ></el-input>
                </el-form-item>
                <div class="char-count">总字数：{{ totalChars }}/500</div>
                <div class="fs14 color-warning">
                  <i class="el-icon-warning"></i>
                  请至少填写一个类别的指标。将体现于商品详情展示(500字以内)。
                </div>
              </el-form-item>
            </el-col>
            <el-col
              v-else
              :span="24"
            >
              <el-form-item
                label="服务产品成果指标"
                label-width="180px"
              >
                <el-input
                  type="textarea"
                  :rows="6"
                  placeholder="请输入服务产品成果指标,如经济指标、质量指标、效率指标或其他指标"
                  v-model="serviceData.achievement"
                  maxlength="3000"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="服务产品详情"
                prop="productDetail"
                label-width="180px"
              >
                <tiny-editor v-model="serviceData.productDetail" />
                <div class="fs14 color-warning"><i class="el-icon-warning" />丰富产品介绍，包含服务内容、技术参数、人员资质等内容。该栏支持文字及图片描述，产品上架后将直接用于产品详情展示。</div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <div class="submit_box">
                  <el-button
                    type="primary"
                    plain
                    @click="saveOrApplyProduct(false)"
                    style="width: 120px"
                    v-loading="saveBtnLoading"
                  >
                    暂时保存
                  </el-button>
                  <!-- <el-button type="primary"  plain @click="" style="width: 120px;margin-left: 20px;">上架预览
                    </el-button> -->
                  <el-button
                    type="primary"
                    v-loading="applyBtnLoading"
                    style="width: 120px;margin-left: 20px;"
                    @click="saveOrApplyProduct(true)"
                  >申请上架
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import InputNumberRange from "@/components/inputNumberRange";
import {
  getProductOweDetail,
  getProductTypeList,
  saveProduct,
  getAgentInfo,
  patentSupportFile,
  contactSupportFile,
  availableProductTypeList,
} from "@/api/homeApi";
import TinyEditor from "@/components/TinyEditor";
import uploadImage from "@/components/upload/uploadImage.vue";
import uploadFile from "@/components/upload/uploadFile";
export default {
  data() {
    var marketPriceValidator = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("市场指导价不能为空"));
      }
      if (parseFloat(value) <= parseFloat(this.serviceData.servicePrice)) {
        callback(new Error("市场指导价必须大于平台优惠价"));
      } else {
        callback();
      }
    };
    // 添加手机号验证函数
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!value) {
        callback(new Error("请输入联系人电话"));
      } else if (!phoneRegex.test(value)) {
        callback(new Error("请输入正确的手机号码。不能输入座机"));
      } else {
        callback();
      }
    };
    return {
      formLoading: false,
      serviceTypeData: [],
      productId: "",
      auditStatus: "",
      serviceData: {
        productName: "",
        productTypeId: "",
        servicePrice: null,
        marketPrice: null,
        priceCalculationProcess: "",
        contactPerson: "",
        contactPhoneNum: "",
        productImg: [],
        serviceContent: "",
        deliveryContent1: "",
        deliveryContent2: "",
        deliveryContent3: "",
        deliveryContent4: "",
        productDetail: "",
        patent: "",
        advantage: "",
        achievement: null,
        quality: "",
        efficiency: "",
        economic: "",
        other: "",
        patentSupportFile: "",
        patentSupportFileName: "",
        contactSupportFile: "",
        contactSupportFileName: "",
        digitalSubtype: [],
        digitalIndustry: [],
        digitalScenarios: [],
        parentProductTypeId: "",
        fastGoodShelf: 0,
        onLineShelf: 0,
      },
      serviceRules: {
        productName: [
          { required: true, message: "请输入服务名称", trigger: "blur" },
        ],
        productTypeId: [
          { required: true, message: "请选择服务类型", trigger: "change" },
        ],
        servicePrice: [
          { required: true, message: "请输入平台优惠价", trigger: "blur" },
        ],
        marketPrice: [
          { required: true, validator: marketPriceValidator, trigger: "blur" },
        ],
        contactPerson: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactPhoneNum: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
        priceCalculationProcess: [
          {
            required: true,
            message: "请输入产品价格测算过程",
            trigger: "blur",
          },
        ],
        productImg: [
          { required: true, message: "请上传服务产品主图", trigger: "change" },
        ],
        serviceContent: [
          { required: true, message: "请输入服务产品介绍", trigger: "blur" },
        ],
        deliveryContent1: [
          { required: true, message: "请输入服务功能介绍", trigger: "blur" },
        ],
        productDetail: [
          { required: true, message: "请输入服务产品详情", trigger: "blur" },
        ],
        achievement: [{ validator: this.validateAchievement, trigger: "blur" }],
        digitalSubtype: [
          {
            required: true,
            message: "请选择产品类型分类",
            trigger: "change",
          },
        ],
        digitalIndustry: [
          {
            required: true,
            message: "请选择行业分类",
            trigger: "change",
          },
        ],
        digitalScenarios: [
          {
            required: true,
            message: "请选择场景分类",
            trigger: "change",
          },
        ],
      },
      uploadPictureVisible: false,
      uploadPicturePreviewUrl: "",
      saveBtnLoading: false,
      applyBtnLoading: false,
      getFromTab: 0,
      uploadFlag: false,
      patentSupportFile: "",
      patentSupportFileFromDetail: "",
      contactSupportFile: "",
      contactSupportFileFromDetail: "",
      isNegotiablePrice: false,
      digitalSubtypeOptions: [],
      digitalIndustryOptions: [],
      digitalScenariosOptions: [],
      showServiceContentConfirm: false,
      showPreviewDialog: false,
      serviceContentTipShown: false,
    };
  },
  components: {
    TinyEditor,
    InputNumberRange,
    uploadImage,
    uploadFile,
  },
  computed: {
    totalChars() {
      return (
        (this.serviceData.quality?.length || 0) +
        (this.serviceData.efficiency?.length || 0) +
        (this.serviceData.economic?.length || 0) +
        (this.serviceData.other?.length || 0)
      );
    },
    commonDict() {
      return this.$store.state.common.commonDict;
    },
  },
  mounted() {
    let query = this.$route.query;
    if (Object.keys(query).length > 0) {
      this.getFromTab = query?.from;
      if (query.id) {
        this.productId = query.id;
        this.getProductInfo(query.id);
      }
    }
    // 获取服务类型
    this.getProductType();
    this.getAgentInfoInput();
    if (this.commonDict.length === 0) {
      this.$store.dispatch("getCommonDict").then(() => {
        this.initDigitalOptions();
      });
    } else {
      this.initDigitalOptions();
    }
  },
  methods: {
    inputMarket(val) {
      // this.marketPrice = val
    },
    inputPlatform(val) {
      // this.platformPrice = val
    },
    handleServiceTypeChange(value) {
      console.log("cascader value:", value);

      // 级联选择器返回的是一个数组，包含选中项的路径
      if (!value || value.length === 0) {
        this.serviceData.parentProductTypeId = "";
        this.isNegotiablePrice = false;
        return;
      }

      // 获取选中的值（最后一级的值）
      const selectedValue = value[value.length - 1];

      // 在级联数据中查找选中的项
      let selectedType = null;

      const findSelectedItem = (options) => {
        for (const option of options) {
          // 检查当前节点是否匹配
          if (option.value === selectedValue) {
            selectedType = option;
            return true;
          }
          // 递归检查子节点
          if (option.children && option.children.length > 0) {
            if (findSelectedItem(option.children)) {
              return true;
            }
          }
        }
        return false;
      };

      findSelectedItem(this.serviceTypeData);

      // 设置父级ID（使用第一级作为parentProductTypeId）
      this.serviceData.parentProductTypeId = value[0] || "";


      // 设置定价类型
      this.isNegotiablePrice = selectedType?.pricingType === 2;

      // 如果是面议价格类型，清空价格字段
      if (this.isNegotiablePrice) {
        this.serviceData.servicePrice = null;
        this.serviceData.marketPrice = null;
      }
      // 清空数字化转型相关字段（如果需要）
      if (value[0] !== "33ac82ab-3ab4-46ce-bfd7-105fc62c4eac") {
        this.serviceData.digitalSubtype = [];
        this.serviceData.digitalIndustry = [];
        this.serviceData.digitalScenarios = [];
      }
    },
    validateAchievement(rule, value, callback) {
      if (this.totalChars === 0) {
        callback(new Error("请至少填写一个类别的指标"));
      } else if (this.totalChars > 500) {
        callback(new Error("总字数不能超过500"));
      } else {
        callback();
      }
    },
    setDefaultImage(event) {
      event.target.src = require("@/assets/image/error.jpg");
    },
    removeImage(index) {
      this.serviceData.productImg.splice(index, 1); // Remove the image at the given index
      //调用uploadImg组件的方法，清除已上传的图片
      this.$refs.uploadImg.outSideRemoveFile(index);
    },
    goBackList() {
      this.$router.go(-1);
    },
    upLoadPatentSupportFile({ fileId, fileName }) {
      this.patentSupportFile = fileId;
      this.serviceData.patentSupportFile = fileId;
      this.serviceData.patentSupportFileName = fileName;
    },
    upLoadContactSupportFile({ fileId, fileName }) {
      this.contactSupportFile = fileId;
      this.serviceData.contactSupportFile = fileId;
      this.serviceData.contactSupportFileName = fileName;
    },
    downloadProofFile() {
      if (!this.productId) {
        this.$message.error("暂不支持预览，请先保存产品信息");
        return;
      }
      patentSupportFile({ productId: this.productId }).then((res) => {
        if (res.code === 200) {
          if (res.data.token) {
            window.open(
              process.env.VUE_APP_BASE_API +
                `/public/file/v1/temp/get?token=${res.data.token}`
            );
          }
        }
      });
    },
    downloadSupportFile() {
      if (!this.productId) {
        this.$message.error("暂不支持预览，请先保存产品信息");
        return;
      }
      contactSupportFile({ productId: this.productId }).then((res) => {
        if (res.code === 200) {
          if (res.data.token) {
            window.open(
              process.env.VUE_APP_BASE_API +
                `/public/file/v1/temp/get?token=${res.data.token}`
            );
          }
        }
      });
    },
    setProductImages(files) {
      // files已经在组件能内push了，这里直接赋值即可
      this.serviceData.productImg = files;
      console.log("productImg", this.serviceData.productImg, files);
      this.uploadFlag = true;
    },
    getProductType() {
      availableProductTypeList().then((res) => {
        if (res.code === 200) {
          // this.serviceTypeData = [...res.data];
          // this.serviceTypeData.forEach((item) => {
          //   item.productTypeName =
          //     item.productTypeName + "(" + item.parentProductTypeName + ")";
          // });
          const groupedData = {};

          res.data.forEach((item) => {
            const parentId = item.parentProductTypeId;

            if (!groupedData[parentId]) {
              groupedData[parentId] = {
                label: item.parentProductTypeName,
                value: item.parentProductTypeId,
                children: [],
              };
            }

            groupedData[parentId].children.push({
              label: item.productTypeName,
              value: item.productTypeId,
              ...item,
            });
          });

          // 转换为数组格式
          this.serviceTypeData = Object.values(groupedData);
        }
      });
    },
    getAgentInfoInput() {
      getAgentInfo().then((res) => {
        if (res.code === 200) {
          this.serviceData.contactPerson = res.data.agentName;
          this.serviceData.contactPhoneNum = res.data.currentUserPhoneNum;
        }
      });
    },
    async getPationSupportFile(productId) {
      try {
        const res = await patentSupportFile({ productId });
        if (res.code === 200) {
          this.patentSupportFileFromDetail = res.data.token;
        } else {
          this.patentSupportFileFromDetail = null;
        }
      } catch (error) {
        console.error("Error fetching patent support file:", error);
        this.patentSupportFileFromDetail = "";
      }
    },
    async getContactSupportFile(productId) {
      try {
        const res = await contactSupportFile({ productId });
        if (res.code === 200) {
          this.contactSupportFileFromDetail = res.data.token;
        } else {
          this.contactSupportFileFromDetail = null;
        }
      } catch (error) {
        console.error("Error fetching patent support file:", error);
        this.contactSupportFileFromDetail = "";
      }
    },
    async getProductInfo(productId) {
      // this.formLoading = true
      // 先获取专利辅助文件
      await this.getPationSupportFile(productId);
      // 相关服务资质佐证文件
      await this.getContactSupportFile(productId);
      getProductOweDetail({
        productId,
      })
        .then((res) => {
          if (res.code === 200) {
            let productImg = res.data.productImg.includes("|")
              ? res.data.productImg.split("|")
              : [res.data.productImg];
            let diyObj = {
              productImg: productImg,
              servicePrice: res.data.limitOriginalPrice / 100,
              marketPrice: res.data.limitMarketGuidancePrice / 100,
              economic: "",
              quality: "",
              efficiency: "",
              other: "",
              digitalScenarios: res.data.digitalScenarios?.split(","),
              digitalIndustry: res.data.digitalIndustry?.split(","),
            };
            this.auditStatus = res.data.auditStatus;
            this.isNegotiablePrice = res.data.pricingType === 2;
            // 分割成果指标到各分类
            if (!this.isNegotiablePrice) {
              const achievementParts = res.data.achievement.split("\n\n");
              achievementParts.forEach((part) => {
                if (part.startsWith("经济指标：")) {
                  diyObj.economic = part.replace("经济指标：", "");
                } else if (part.startsWith("质量指标：")) {
                  diyObj.quality = part.replace("质量指标：", "");
                } else if (part.startsWith("效率指标：")) {
                  diyObj.efficiency = part.replace("效率指标：", "");
                } else if (part.startsWith("其他指标：")) {
                  diyObj.other = part.replace("其他指标：", "");
                }
              });
            }
            this.serviceData = Object.assign(res.data, diyObj);
          }
        })
        .finally(() => {
          // this.formLoading = false
        });
    },
    // 产品暂存或者上架
    saveOrApplyProduct(applyForLaunch) {
      let self = this;
      self.$refs["serviceForm"].validate((valid) => {
        if (valid) {
          // 合并成果指标
          if (!self.isNegotiablePrice) {
            self.serviceData.achievement =
              `经济指标：${self.serviceData.economic}\n\n` +
              `质量指标：${self.serviceData.quality}\n\n` +
              `效率指标：${self.serviceData.efficiency}\n\n` +
              `其他指标：${self.serviceData.other}`;
          }
          let data = {
            applyForLaunch,
            pricingType: self.isNegotiablePrice ? 2 : 1,
          };
          Object.keys(self.serviceData).forEach((i) => {
            if (i === "servicePrice") {
              if (!self.isNegotiablePrice) {
                data["limitOriginalPrice"] = self.serviceData[i] * 100;
                data["upperOriginalPrice"] = self.serviceData[i] * 100;
              } else {
                data["limitOriginalPrice"] = null;
                data["upperOriginalPrice"] = null;
              }
            } else if (i === "marketPrice") {
              if (!self.isNegotiablePrice) {
                data["limitMarketGuidancePrice"] = self.serviceData[i] * 100;
                data["upperMarketGuidancePrice"] = self.serviceData[i] * 100;
              } else {
                data["limitMarketGuidancePrice"] = null;
                data["upperMarketGuidancePrice"] = null;
              }
            } else if (
              [
                "digitalSubtype",
                "digitalIndustry",
                "digitalScenarios",
              ].includes(i)
            ) {
              // 确保这些字段是数组，并且元素转换为整数
              if (Array.isArray(self.serviceData[i])) {
                data[i] = self.serviceData[i].map(Number);
              } else if (self.serviceData[i]) {
                // 如果是单个值，转换为只包含一个元素的数组
                data[i] = [Number(self.serviceData[i])];
              } else {
                data[i] = [];
              }
            } else {
              data[i] = self.serviceData[i];
            }
          });
          applyForLaunch
            ? (self.applyBtnLoading = true)
            : (self.saveBtnLoading = true);
          // this.serviceData, 'productImg'需要将数组转字符串, 多个图像|分隔, 如果productImg是空数组，有防止报错机制
          data.productImg = self.serviceData.productImg?.join("|");
          // console.log(data.productTypeId);
          // console.log(typeof data.productTypeId);
          // console.log(data.productTypeId.length);
          if(Array.isArray(data.productTypeId) && data.productTypeId.length > 1){
            data.productTypeId = data.productTypeId[1]
          }
          
          saveProduct(data)
            .then((res) => {
              if (res.code == 200) {
                self.$message.success(
                  `${
                    applyForLaunch ? "服务产品信息提交" : "服务产品信息暂存"
                  }成功！`
                );
                self.productId = res.data.productId;
                self.goBackList();
              }
            })
            .finally(() => {
              applyForLaunch
                ? (self.applyBtnLoading = false)
                : (self.saveBtnLoading = false);
            });
        } else {
          // 弹出confirm提示框，请 根据红色提示填完必填信息, 只有确定按钮
          self
            .$confirm("请根据红色提示填完必填信息", "提示", {
              confirmButtonText: "确定",
              showCancelButton: false,
              type: "warning",
            })
            .then(() => {
              // 确定
            });
        }
      });
    },
    initDigitalOptions() {
      for (const item of Object.values(this.commonDict)) {
        if (item.dictType === "sme_digital_subtype") {
          this.digitalSubtypeOptions = item.dictData;
        }
        if (item.dictType === "sme_digital_industry") {
          this.digitalIndustryOptions = item.dictData;
        }
        if (item.dictType === "sme_digital_scenarios") {
          this.digitalScenariosOptions = item.dictData;
        }
      }
    },
    handleServiceContentBlur() {
      if (!this.serviceContentTipShown) {
        this.showServiceContentConfirm = true;
        this.serviceContentTipShown = true;
      }
    },
  },
};
</script>

<style scoped>
p {
  margin: 0;
  padding: 0;
}

.submit_box {
  margin-top: 42px;
  width: 100%;
  text-align: center;
}
/deep/.el-divider--horizontal {
  margin: 16px 0;
}
</style>
